package org.example.system.common.utils;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.example.system.common.dto.SearchItemDto;

import java.util.List;


/**
 * MybatisPlus搜索工具类
 * @author joey
 */
public class MybatisPlusSearchUtil {
    public static final String EQ="eq";
    public static final String NE="ne";
    public static final String LIKE="like";
    public static final String LIKE_LEFT="likeLeft";
    public static final String LIKE_RIGHT="likeRight";
    public static final String NOT_LIKE="notLike";
    public static final String GT="gt";
    public static final String LT="lt";
    public static final String GE="ge";
    public static final String LE="le";

    /**
     * 构造QueryWrapper
     * @param searchJson
     * @return
     */
    public static QueryWrapper parseWhereSql(String searchJson){
        QueryWrapper queryWrapper = new QueryWrapper();
        if(StrUtil.isNotEmpty(searchJson)){
            List<SearchItemDto> searchList = JSONUtil.toList(JSONUtil.parseArray(searchJson), SearchItemDto.class);
            if(CollUtil.isNotEmpty(searchList)){
                for(SearchItemDto form : searchList){
                    if(StrUtil.isEmpty(form.getKey())){
                        continue;
                    }
                    if(StrUtil.isEmpty(form.getValue())){
                        continue;
                    }
                    if(StrUtil.isEmpty(form.getType())){
                        queryWrapper.eq(form.getKey(),form.getValue());
                    }else {
                        switch (form.getType()){
                            case EQ : queryWrapper.eq(form.getKey(),form.getValue());break;
                            case NE : queryWrapper.ne(form.getKey(),form.getValue());break;
                            case LIKE : queryWrapper.like(form.getKey(),form.getValue());break;
                            case LIKE_LEFT : queryWrapper.likeLeft(form.getKey(),form.getValue());break;
                            case LIKE_RIGHT : queryWrapper.likeRight(form.getKey(),form.getValue());break;
                            case NOT_LIKE : queryWrapper.notLike(form.getKey(),form.getValue());break;
                            case GT : queryWrapper.gt(form.getKey(),form.getValue());break;
                            case LT : queryWrapper.lt(form.getKey(),form.getValue());break;
                            case GE : queryWrapper.ge(form.getKey(),form.getValue());break;
                            case LE : queryWrapper.le(form.getKey(),form.getValue());break;
                            default:
                        }
                    }
                }
            }
        }
        return queryWrapper;
    }
}
